<template>
  <div>
    <el-form ref="ruleForm" :disabled="formDis" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" style="margin-top: 20px;">
      <el-form-item v-if="selectShow" label="课程类型" prop="type">
        <el-select v-model="ruleForm.type" placeholder="请选择课程类型">
          <el-option :value="0" label="禅修" />
          <el-option :value="1" label="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="课程标题" prop="title">
        <el-col :span="12" >
          <el-input v-model="ruleForm.title" maxlength="100" />
        </el-col>
      </el-form-item>
      <el-form-item label="课程费用" prop="cost">
        <el-col :span="6" >
          <el-input v-model="ruleForm.cost" type="number" />
        </el-col>
        &nbsp;&nbsp;元
      </el-form-item>
      <el-form-item label="销售价格" prop="discount">
        <el-col :span="6" >
          <el-input v-model="ruleForm.discount" type="number" />
        </el-col>
        &nbsp;&nbsp;元
      </el-form-item>
      <el-form-item label="分销底价" prop="reservePrice">
        <el-col :span="6" >
          <el-input v-model="ruleForm.reservePrice" type="number" />
        </el-col>
        &nbsp;&nbsp;元
        <p class="tip">提示：分销底价需小于销售价格</p>
      </el-form-item>
      <el-form-item label="分享提成" prop="signupCommission">
        <el-col :span="6" >
          <el-input v-model="ruleForm.signupCommission" />
        </el-col>
        &nbsp;&nbsp;元
        <p class="tip">提示：分享提成需小于销售价格与分销底价的差值</p>
      </el-form-item>
      <el-form-item label="活动人数" prop="stuNumber">
        <el-col :span="6" >
          <el-input v-model="ruleForm.stuNumber" type="number" />
        </el-col>
        &nbsp;&nbsp;人
      </el-form-item>
      <el-form-item label="地点" prop="address">
        <el-col :span="12">
          <el-input v-model="ruleForm.address" />
        </el-col>
      </el-form-item>
      <el-form-item v-if="selectShow && !formDis" label="讲师" prop="tid">
        <el-select v-model="ruleForm.tid" placeholder="请选择讲师">
          <el-option v-for="(item, index) in teacher" :key="index" :label="item.name" :value="item.tid" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="selectShow && formDis" label="讲师" prop="tid">
        <el-select v-model="ruleForm.teacherName" placeholder="">
          <el-option :label="ruleForm.teacherName" :value="ruleForm.teacherName" />
        </el-select>
      </el-form-item>
      <el-form-item class="add_tip" label="活动时间">
        <el-col :span="5">
          <el-form-item prop="startDate">
            <el-date-picker
              v-model="ruleForm.startDate"
              type="datetime"
              placeholder="选择开始日期" />
          </el-form-item>
        </el-col>
        <el-col :span="2" class="line">-</el-col>
        <el-col :span="5">
          <el-form-item prop="endDate">
            <el-date-picker
              v-model="ruleForm.endDate"
              type="datetime"
              placeholder="选择结束日期" />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item class="add_tip" label="封面图片">
        <el-upload
          :before-remove="beforeRemove"
          :before-upload="beforeAvatarUpload"
          :on-success="(file, filelist) => change('coverImg', file, filelist)"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :data="uploadData"
          :action="actionUrl"
          with-credentials
          multiple
          class="upload-demo"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</div>
        </el-upload>
        <img v-show="ruleForm.coverImg" :src="ruleForm.coverImg" :style="ruleForm.coverImg ? 'width: 326px;' : ''" alt="">
      </el-form-item>
      <el-form-item class="add_tip" label="海报图片">
        <el-upload
          :before-remove="beforeRemove"
          :before-upload="beforeAvatarUpload"
          :on-success="(file, filelist) => change('posterImg', file, filelist)"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :data="uploadData"
          :action="actionUrl"
          multiple
          with-credentials
          class="upload-demo"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</div>
        </el-upload>
        <img v-show="ruleForm.posterImg" :src="ruleForm.posterImg" :style="ruleForm.posterImg ? 'width: 326px;' : ''" alt="">
      </el-form-item>
      <el-form-item class="add_tip" label="课程介绍" porp="introduction">
        <div>
          <div v-if="formDis" class="tin_box" v-html="ruleForm.introduction" />
          <tinymce v-else v-model="ruleForm.introduction" :height="300" :disabled="tinymceDis" />
        </div>
      </el-form-item>
      <el-form-item label="课程安排" prop="cPlan">
        <el-input v-model="ruleForm.cPlan" type="textarea" />
        <!-- <div>
          <div v-if="formDis" class="tin_box" v-html="ruleForm.cPlan" />
          <tinymce v-else v-model="ruleForm.cPlan" :height="300" :disabled="tinymceDis" />
        </div> -->
      </el-form-item>
      <el-form-item class="add_tip" label="费用说明" prop="costDesc">
        <el-input v-model="ruleForm.costDesc" type="textarea" />
        <!-- <div>
          <div v-if="formDis" class="tin_box" v-html="ruleForm.costDesc" />
          <tinymce v-else v-model="ruleForm.costDesc" :height="300" :disabled="tinymceDis" />
        </div> -->
      </el-form-item>
      <el-form-item label="注意事项" prop="precautions">
        <el-input v-model="ruleForm.precautions" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button v-preventReClick v-else type="primary" @click="submitForm('ruleForm')">新增</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from '@/utils/config';
import { checkPhone, checkIdCard, checkEmail } from '@/utils/regUtil';
import { checkNotEmail, checkNum, checkStudentNum } from '@/utils/validateUtil';
import { getTeacherList } from '@/api/teacher'
import { addCours, editCours } from '@/api/course'
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'
import mixin from '@/mixin'
import { vipInfoAll } from '@/api/product'

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'));
  } else if (value.toString().length < 6 || value.toString().length > 100) {
    callback(new Error('密码长度为6 - 100个字符'))
  } else {
    callback();
  }
};

const validatephone = (rule, value, callback) => {
  if (!checkPhone(value)) {
    callback(new Error())
  }
  callback()
};
const validateIdCard = (rule, value, callback) => {
  if (!checkIdCard(value)) {
    callback(new Error())
  }
  callback()
};
const validateMail = (rule, value, callback) => {
  if (!checkNotEmail(value)) {
    callback(new Error())
  }
  callback()
};
// const validateNum = (rule, value, callback) => {
//   if (!checkNum(value)) {
//     callback(new Error())
//   }
//   callback()
// };
const validateStudentNum = (rule, value, callback) => {
  if (!checkStudentNum(value)) {
    callback(new Error())
  }
  callback()
};

const validateStudentNumber = (rule, value, callback) => {
  if (value.length > 5) {
    callback(new Error())
  }
  callback()
};

const validateZero = (rule, value, callback) => {
  if (!checkNum(value)) {
    callback(new Error())
  }
  callback()
};

export default {
  components: { Tinymce },
  mixins: [mixin],
  data() {
    return {
      teacher: [],
      rules: {
        type: [
          { required: true, message: '请选择课程类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入课程标题', trigger: 'blur' },
          { max: 100, message: '输入字符不得超过100个', trigger: 'blur' }
        ],
        cost: [
          { required: true, message: '请输入课程费用', trigger: 'blur' },
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '请输入销售价格', trigger: 'blur' },
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        reservePrice: [
          { required: true, message: '请输入分销底价', trigger: 'blur' },
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        signupCommission: [
          { required: true, message: '请输入分享提成', trigger: 'blur' },
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        stuNumber: [
          { required: true, message: '请输入学生人数', trigger: 'blur' },
          { validator: validateStudentNum, message: '请输入整数', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '活动人数需大于0', trigger: 'blur' },
          { validator: validateStudentNumber, message: '长度为1-5位数字', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 12, max: 40, message: '长度12-40个字符', trigger: 'blur' }
        ],
        tid: [
          { required: true, message: '请选择讲师', trigger: 'change' }
        ],
        introduction: [
          { required: true, message: '课程介绍不能为空', trigger: 'blur' }
        ],
        cPlan: [
          { required: true, message: '课程安排不能为空', trigger: 'blur' },
          { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        ],
        costDesc: [
          { required: true, message: '费用说明不能为空', trigger: 'blur' },
          { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        ],
        precautions: [
          { required: true, message: '注意事项不能为空', trigger: 'blur' },
          { max: 1000, message: '长度不能超过1000个字符', trigger: 'blur' }
        ]
      },
      fileList: [],
      actionUrl: config.BaseUrl + '/image/upload',
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      tinymceDis: false,
      isEdit: false,
      selectShow: false,
      // 对应<请选择讲师下拉菜单>查询教师信息列表时，把status为1的教师获取出来
      listQuery: {
        pageNum: 0,
        pageSize: 1000,
        status: 1
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      isDisabled: false
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
    ruleForm: {
      handler: function(nowVal, oldVal) {
        this.$store.dispatch('AddlistenForm', this.ruleForm).then(() => {
        }).catch((err) => {
          Message.error(err.err)
        })
      },
      deep: true
    }
  },
  created() {
  },
  mounted() {
    const _self = this;
    console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      const a = this.$route.query
      if (a.hasOwnProperty('isLook')) {
        this.dataToHtml(a)
        this.selectShow = true
        delete a.isLook;
      }
      if (a.hasOwnProperty('isEdit')) {
        this.dataToHtml(a)
        this.getTeacherList()
        delete a.isEdit;
      }
      this.$store.dispatch('AddlistenForm', this.$route.query).then(() => {
      }).catch((err) => {
        Message.error(err.err)
      })
    } else { // 新增
      this.getTeacherList()
      this.$store.dispatch('resetFunc').then(() => {
      }).catch((err) => {
        Message.error(err.err)
      })
    }
    this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    request(data) {
      data.startDate = new Date(data.startDate).getTime();
      data.endDate = new Date(data.endDate).getTime();
      this.dataToCode(data)
      this.isEdit ? editCours(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('编辑成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      }) : addCours(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('新增成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      });
    },
    dataToHtml(query) {
      query.cPlan = this.changeToHtml(query.cPlan)
      query.costDesc = this.changeToHtml(query.costDesc)
      query.precautions = this.changeToHtml(query.precautions)
    },
    dataToCode(data) {
      data.cPlan = this.changeToCode(data.cPlan)
      data.costDesc = this.changeToCode(data.costDesc)
      data.precautions = this.changeToCode(data.precautions)
    },
    changeToCode(str) {
      return str.replace(/\r\n|\r|\n/g, '<br/>')
    },
    changeToHtml(str) {
      return str.replace(/<br\s*\/?>/g, '\n')
    },
    getTeacherList() {
      getTeacherList(this.listQuery).then(response => {
        this.teacher = response.data.list
        console.log(this.teacher.length)
        this.selectShow = true
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm)
          if (new Date(this.ruleForm.startDate).getTime() >= new Date(this.ruleForm.endDate).getTime()) {
            Message.error('活动开始时间必须小于结束时间')
            return false
          }
          if (new Date(this.ruleForm.startDate).getTime() <= new Date().getTime()) {
            Message.error('活动开始时间必须大于当前时间')
            return false
          }
          if (new Date(this.ruleForm.endDate).getTime() <= new Date().getTime()) {
            Message.error('活动结束时间必须大于当前时间')
            return false
          }
          this.request(this.ruleForm)
        } else {
          this.validateError()
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$store.dispatch('resetFunc').then(() => {
      }).catch((err) => {
        Message.error(err.err)
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {})
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isPNG && !isJPEG && !isJPG && !isGIF) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
    },
    change(type, file, fileList) {
      if (Number(fileList.response.code) === 200) {
        let obj;
        switch (type) {
          case 'coverImg':
            obj = {
              coverImg: config.ImgUrl + fileList.response.data
            };
            break;
          case 'posterImg':
            obj = {
              posterImg: config.ImgUrl + fileList.response.data
            };
            break;
        }
        this.$store.dispatch('addListenerCoverImg', obj).then(() => {
          Message.success('图片上传成功')
        }).catch((err) => {
          Message.error(err.err)
        })
      }
    }
  }
}
</script>

<style>
  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
</style>
